import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;

/**
 * @Author:liruo
 * @Date:2023-04-30-19:59:16
 * @Desc
 */
public class ParseURI {
    @RequestMapping({
            "/aci",
    })
    public interface ACI{
        @GetMapping(path = "/f1",
                consumes =  MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE
        )
        void f1();
    }
    @RestController
    public static class AC implements ACI{
        @Override
        public void f1() {

        }
    }
    @Test
    public void test1() {
        Class<AC> controllerClass = AC.class;
        Class<?> mapping = null;
        if(controllerClass.getAnnotation(RequestMapping.class) != null){
            mapping = controllerClass;
        }else{
            for (Class<?> anInterface : controllerClass.getInterfaces()) {
                if(anInterface.getAnnotation(RequestMapping.class) != null){
                    mapping = anInterface;
                    break;
                }
            }
        }

        if(mapping == null){
            System.err.println(controllerClass.getName() + " has not api");
            return;
        }
        RequestMapping root = mapping.getAnnotation(RequestMapping.class);
        if(root.value().length != 1){
            System.err.printf("%s  root prefix has %d uri prefix\n",
                    controllerClass.getName(),
                    root.value().length);
            return;
        }
        String uriPrefix = root.value()[0];
        for (Method method : mapping.getDeclaredMethods()) {
            System.out.println(getMappingAttrs(method.getDeclaredAnnotations()));
        }
    }

    public static Map<String, Object> getMappingAttrs(Annotation[] annotations){
        Map<String, Object> attrs;
        for (Annotation annotation : annotations) {
            Class<? extends Annotation> annotationType = annotation.annotationType();
            if(annotationType.getName().endsWith("Mapping")){
                attrs = AnnotationUtils.getAnnotationAttributes(annotation);
                attrs.put("method", AnnotationUtils.getAnnotationAttributes(annotationType
                        .getDeclaredAnnotation(RequestMapping.class)).get("method"));
                return attrs;
            }
        }
        return Collections.emptyMap();
    }
}
